<template>
  <div class="container flex_cc">
    <div class="login_box">
      <img
        src="@/assets/img/login_left.png"
        style="width: 672px; height: 100%"
        alt=""
      />
      <div>
        <div class="flex" style="margin-bottom: 50px">
          <img
            src="@/assets/img/icon_house.png"
            style="width: 32px; height: 38px; margin-right: 6px"
            alt=""
          />
          <div class="fs_24 fw gradient-text">必劢科技后台运营管理系统</div>
        </div>
        <el-form
          style="width: 350px"
          :model="login_from"
          label-width="0"
          :rules="loginRules"
          ref="ruleLoginForm"
        >
          <el-form-item prop="account">
            <el-input
              placeholder="请输入账号"
              style="height: 46px; width: 100%"
              v-model="login_from.account"
              ><template #prefix>
                <svgBtn
                  icon="account"
                  style="font-size: 20px"
                ></svgBtn> </template
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              placeholder="请输入密码"
              type="password"
              style="height: 46px; width: 100%"
              v-model="login_from.password"
              @keyup.enter="login(ruleLoginForm)"
              ><template #prefix>
                <svgBtn
                  icon="password"
                  style="font-size: 20px"
                ></svgBtn> </template
            ></el-input>
          </el-form-item>
          <div class="flex_js">
            <div class="flex">
              <el-checkbox v-model="remerber_me"></el-checkbox>
              <span class="m_left10">记住我</span>
            </div>

            <div style="color: #3580eb">找回密码</div>
          </div>
          <el-button
            @click="login(ruleLoginForm)"
            style="width: 100%; height: 48px; margin-top: 60px"
            type="primary"
            :loading="loading"
            >登录<span v-if="loading">中...</span></el-button
          >
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import svgBtn from '@/components/svg_button.vue'
import { FormInstance, ElMessage } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import { getCookie, setCookie } from '@/utils/cookie'
import { isArray } from 'lodash'
// type FormInstance = InstanceType<typeof ElForm>
const ruleLoginForm = ref<FormInstance>()
const loginRules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}
const loading = ref(false)
const router = useRouter()
const store = useStore()
const login_from = ref({
  account: getCookie('account'),
  password: getCookie('password'),
})

const remerber_me = ref(login_from.value.account == '' ? false : true)
const login = (e) => {
  if (!e) return
  e.validate((valid) => {
    if (valid) {
      if (loading.value) return
      loading.value = true
      axios
        .request({
          url: serviceApi.login,
          method: 'post',
          data: login_from.value,
        })
        .then((res) => {
          console.log(res)
          setCookie('bimai_admin_token', res.data, 1, '/') // 存token 到cookie
          if (remerber_me.value) {
            setCookie('account', '', -1)
            setCookie('password', '', -1)
            setCookie('account', login_from.value.account, 1)
            setCookie('password', login_from.value.password, 1)
          } else {
            setCookie('account', '', -1)
            setCookie('password', '', -1)
          }
          get_role_list()
        })
        .catch((err) => {
          loading.value = false
          ElMessage.error(err)
        })
    } else {
    }
  })
}
const get_user_info = async () => {
  axios
    .request({ url: serviceApi.user_crud, method: 'get' })
    .then((res) => {
      console.log(res)
      let user_info = {
        username: res.data.username,
        headPic: res.data.headPic,
        id: res.data.id,
        is_admin: res.data.isAdmin,
      }
      store.commit('set_user_info', user_info)
      if (res.data.isAdmin) {
        // 超管
        set_admin_role()
        return
      }
      var axios_list = []
      for (let i in res.data.userRoleDTOList) {
        axios_list[i] = new Promise((resolve) => {
          axios
            .request({
              url:
                serviceApi.role_crud + '/' + res.data.userRoleDTOList[i].roleId,
              method: 'get',
            })
            .then((res1) => {
              resolve(res1.data.roleRouteDTOList)
            })
            .catch((err) => {
              loading.value = false
              ElMessage.error(err)
            })
        })
      }
      Promise.all(axios_list).then(async (res) => {
        // 权限存储
        console.log(res)
        var role_list = [] // 权限列表
        var list = []
        // 多角色处理
        for (let i in res) {
          if (isArray(res[i])) {
            list = list.concat(res[i])
          }
        }
        // 相同权限去重
        var obj = {}
        list = list.reduce(function (item, next) {
          obj[next.routeId] ? '' : (obj[next.routeId] = true && item.push(next))
          return item
        }, [])
        for (let i in list) {
          for (let ii in base_role_list.value) {
            if (base_role_list.value[ii].id == list[i].routeId) {
              console.log(base_role_list.value[ii].name)
              role_list.push(base_role_list.value[ii])
            }
          }
        }
        console.log(arrToTree(role_list))
        await store.commit('set_role_arr', sortByKey(role_list, 'id'))
        await store.commit('set_role_list', arrToTree(role_list))
        await store.commit('clear_tabs_list')
        loading.value = false
        router.push({ name: 'home' })
      })
    })
    .catch((err) => {
      loading.value = false
      ElMessage.error(err)
    })
}
const set_admin_role = async () => {
  var list = []
  for (let ii in base_role_list.value) {
    if (base_role_list.value[ii].platformType != 2) {
      list.push(base_role_list.value[ii])
    }
  }
  console.log(arrToTree(list))
  await store.commit('set_role_arr', sortByKey(list, 'sort'))
  await store.commit('set_role_list', arrToTree(sortByKey(list, 'sort')))
  await store.commit('clear_tabs_list')
  loading.value = false
  router.push({ name: 'home' })
}
const sortByKey = (array, key) => {
  // 菜单排序
  return array.sort(function (a, b) {
    var x = a[key]
    var y = b[key]
    return x < y ? -1 : x > y ? 1 : 0
  })
}
const arrToTree = (list) => {
  var map = {}
  var result = []
  list.forEach((item) => {
    map[item.id] = item
  })
  list.forEach((item) => {
    item.label = item.name
    item.value = item.id
    let parent = map[item.parentId]
    if (parent && item.type != 4) {
      if (!parent.children) {
        parent.children = []
        parent.children.push(item)
      } else {
        var a = parent.children.some((e) => {
          return e.id == item.id
        })
        console.log(a)
        if (!a) {
          parent.children.push(item)
        }
      }
      parent.children.sort(function (a, b) {
        return a.sort - b.sort
      })
    } else if (!parent && item.type != 4) {
      result.push(item)
    }
  })
  return result
}
const base_role_list = ref()
const get_role_list = () => {
  axios
    .request({ url: serviceApi.router_list, method: 'post' })
    .then((res) => {
      console.log(res)
      base_role_list.value = res.data
      get_user_info()
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
</script>

<style lang="scss" scoped>
.svgButton {
  line-height: 44px;
}
:deep(.el-input--prefix .el-input__inner) {
  padding-left: 40px;
}
:deep(.el-input__inner) {
  height: 46px;
}
.login_box {
  background-color: #fff;
  border-radius: 4px;
  width: 1200px;
  height: 675px;
  display: flex;
  align-items: center;
  animation: box_opacity 0.8s linear 1;
  > div {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
.container {
  height: 100%;
  background-image: url('@/assets/img/login_bg.png');
  background-size: 100% 100%;
}
@keyframes box_opacity {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>
